package org.jeecg.modules.scheduling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.ibatis.annotations.Param;
import org.jeecg.modules.scheduling.entity.*;
import org.jeecg.modules.scheduling.mapper.SchedulingMapper;
import org.jeecg.modules.scheduling.service.ISchedulingService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 排班表
 * @Author: jeecg-boot
 * @Date:   2025-01-21
 * @Version: V1.0
 */
@Service
public class SchedulingServiceImpl extends ServiceImpl<SchedulingMapper, Scheduling> implements ISchedulingService {

    @Override
    public List<EmployeeSchedule> getSchedulingRecord(String month, String name, String workNumber, String departmentId) {
        try {
            List<Map<String, Object>> rawData = baseMapper.getSchedulingRecord(month, name, workNumber, departmentId);
            Map<String, EmployeeSchedule> optimizedData = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            for (Map<String, Object> row : rawData) {
                String employeeName = (String) row.get("name");
                String workNum = (String) row.get("workNumber");
                Object dateObj = row.get("date");
                String date = dateObj instanceof Date ? sdf.format(dateObj) : dateObj.toString();
                String shiftType = (String) row.get("shift_type");

                if (!optimizedData.containsKey(employeeName)) {
                    EmployeeSchedule employeeInfo = new EmployeeSchedule();
                    employeeInfo.setName(employeeName);
                    employeeInfo.setWorkNumber(workNum);
                    optimizedData.put(employeeName, employeeInfo);
                }

                Shift shift = new Shift();
                shift.setType(shiftType);
                EmployeeSchedule employeeInfo = optimizedData.get(employeeName);
                employeeInfo.addShift(date, shift);
            }

            return new ArrayList<>(optimizedData.values());
        } catch (Exception e) {
            // 日志记录异常信息
            log.error("Error occurred while getting scheduling record: ", e);
            throw new RuntimeException("获取排班信息失败", e);
        }
    }

    @Override
    public Scheduling getLastByAdmitGuid(String admitGuid) {
        LambdaQueryWrapper<Scheduling> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Scheduling::getAdmitGuid, admitGuid);
        wrapper.orderByDesc(Scheduling::getCreateTime);
        wrapper.last("limit 1");
        return baseMapper.selectOne(wrapper);
    }

}
